"""
    导出Excel
"""

import os
import openpyxl
from .random_name import now_data
from django.conf import settings


class ExportExcel:
    """
    obj_title: 表头
    obj: 表格内容
    excel_name：表格名称
    """

    def __init__(self, obj, excel_name, obj_title):
        self.obj = obj
        self.excel_name = excel_name
        self.obj_title = obj_title

    def write_to_excel(self, data: list, path: str, obj_dict: dict):
        """把数据写入到Excel"""
        # 实例化一个workbook
        workbook = openpyxl.Workbook()
        # 激活一个sheet
        sheet = workbook.active
        # 准备keys
        data.insert(0, obj_dict)
        keys = data[0].keys()
        # 准备写入数据
        for index, item in enumerate(data):
            # 遍历每一个元素
            for k, v in enumerate(keys):
                sheet.cell(row=index + 1, column=k + 1, value=str(item[v]))
        # 写入到文件
        workbook.save(path)

    def write(self, obj, excel_name, obj_title):

        """导出数据到Excel"""
        # 获取所有的学生信息
        obj = obj
        # 转为list
        obj_list = list(obj)
        obj_dict = dict(obj_title)
        # Excel 文件名称
        excel_to_name = excel_name + "【 " + str(now_data()) + " 】" + ".xlsx"
        # 准备写入路径
        path = os.path.join(settings.EXPORT_ROOT, excel_to_name)
        # 写入到 Excel
        self.write_to_excel(obj_list, path, obj_dict)
        return excel_to_name
